package com.app.micaihu.view.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.GetTaskBean;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Guo on 2016/7/13.
 * <p>
 * 重置密码;找回密码;绑定手机 的 接受验证码的页面
 */
public class ResetPwdActivity extends BaseOldActivity implements View.OnClickListener {


    private EditText etPhoneCode;
    private TextView tvCountdown;
    private EditText etPassword;
    private RadioButton rbShowOrHidePwd;
    private ImageView ivInputCancel;
    private TextView tvConfirm;//确认店家
    private TextView tvPrompt;//提示文本


    private Timer mTimer;//timer
    private static int time;//倒计时
    private static TimerTask mTimerTask;//倒计时任务

    private static boolean mIsSendcode;//是否发送验证码
    //操作倒计时的操作handler
    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (time <= 0 && tvCountdown != null) {
                tvCountdown.setClickable(true);
                tvCountdown.setText("重新发送");
                return;
            }
            if (tvCountdown != null) {
                tvCountdown.setText(time + "s");
            }
        }
    };
    private TextView tvPhoneNum;//本页提示电话的文本
    private Intent intent;//上一个页面的意图
    private String mPhoneNum;//电话文本
    private String actionType;//动作类型
    private String code;//验证码文本
    private String pwd;//密码文本
    private boolean mSelect;//是否选中 显示密码

    private static String typeLoa;//本地保存的type
    private static final String LOCAL_TYPE = "local_type";
//    private String nickname;
//    private String openid;
//    private String avatar;
//    private String fromType;
//    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_resetpassword);
        intent = getIntent();

        initView();
        initListener();


        setTimer();
    }

    private void initView() {


        etPhoneCode = (EditText) findViewById(R.id.et_phonecode);
        tvCountdown = (TextView) findViewById(R.id.tv_countdown);
        etPassword = (EditText) findViewById(R.id.et_password);
        rbShowOrHidePwd = (RadioButton) findViewById(R.id.rb_show_or_hide_pwd);
        ivInputCancel = (ImageView) findViewById(R.id.iv_input_cancel);
        tvConfirm = (TextView) findViewById(R.id.tv_confirm);
        tvPrompt = (TextView) findViewById(R.id.tv_prompt);
        tvPhoneNum = (TextView) findViewById(R.id.tv_phonenum);

        tvConfirm.setEnabled(false);


        if (intent == null) {
            if (tvPhoneNum != null) {
                tvPhoneNum.setVisibility(View.INVISIBLE);
            }
        } else {
            if (tvPhoneNum != null) {
                tvPhoneNum.setVisibility(View.VISIBLE);
                mPhoneNum = intent.getStringExtra("phone");
                tvPhoneNum.setText(mPhoneNum);
            }
        }

        actionType = intent.getStringExtra(TypeConstant.ACTION_TYPE);
        if (TextUtils.isEmpty(typeLoa)) {
            typeLoa = actionType;
        }

        if (TextUtils.equals(actionType, TypeConstant.RESETPWD_ACTION)) {
            setTitle("重置密码");
        } else if (TextUtils.equals(actionType, TypeConstant.FINDPWD_ACTION)) {
            setTitle("找回密码");
        } else if (TextUtils.equals(actionType, TypeConstant.BINDPHONE_ACTION)) {
            setTitle("绑定手机");
        }

    }

    private void initListener() {

        tvCountdown.setOnClickListener(this);
        tvCountdown.setClickable(false);

        tvConfirm.setOnClickListener(this);
        ivInputCancel.setOnClickListener(this);
        rbShowOrHidePwd.setOnClickListener(this);

        etPhoneCode.addTextChangedListener(tw);
        etPassword.addTextChangedListener(tw);

    }

    /**
     * edittext的监听
     */
    TextWatcher tw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etPassword == null || etPhoneCode == null || tvConfirm == null) return;
            if (etPassword.getText().toString().trim().length() >= 6
                    && etPhoneCode.getText().toString().trim().length() >= 4) {
                tvConfirm.setEnabled(true);
            } else {
                tvConfirm.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private void setTimer() {
        /**
         * 如果当前有任务进行则 停止任务从新建立一个任务
         * 如果没有任务进行则判断之前是否执行过任务，如果有则不建立任务
         * 如果没有则建立新的任务
         */

        if (!TextUtils.isEmpty(actionType) && !TextUtils.equals(actionType, typeLoa)) {//证明不是上一次与这一次 进来的页面不同
            sendCode();
            typeLoa = actionType;
        } else {
            if (time > 0) {
                tvCountdown.setText(time + "s");
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                }
                if (mTimer != null) {
                    mTimer.cancel();
                }
                if (mTimer == null) {
                    mTimer = new Timer();
                }
                mTimerTask = new TimerTask() {

                    @Override
                    public void run() {
                        time--;
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0);
                        }
                        if (time <= 0) {
                            cancel();
                        }
                    }
                };
                mTimer.schedule(mTimerTask, 1000, 1000);
            } else if (!mIsSendcode) {
                sendCode();
            } else {
                tvCountdown.setClickable(true);
                tvCountdown.setText("重新发送");
            }
        }
    }


    /**
     * 发送验证码
     */
    private void sendCode() {
        /*if (time > 0) {
            return;
        }*/
        tvCountdown.setClickable(false);

        if (mTimerTask != null) {
            mTimerTask.cancel();
        }

        if (mTimer == null) {
            mTimer = new Timer();
        }
        time = 60;
        tvCountdown.setText(time + "s");
        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                time--;
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0);
                }
                if (time <= 0) {
                    cancel();
                }
            }
        };
//        mTimer.schedule(mTimerTask, 1000, 1000);
        //发送网络请求
        ParamMap paramSend = new ParamMap();
        getParamCode(paramSend, actionType);

        if (paramSend.size() <= 0) {
            ToastUtils.makeText("程序异常,请重新打开本页");
            return;
        }
        addPostRequest(URIContant.SEND_CODE, new TypeToken<DataBean>() {
        }.getType(), paramSend, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                //已发送验证码
                mIsSendcode = true;
                DialogUtils.getInstance().showProgressDialog(ResetPwdActivity.this, "正在发送");
            }

            @Override
            public void onError(VolleyError error) {
                tvPrompt.setText("发送失败");
                tvPrompt.setVisibility(View.GONE);
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
            }

            @Override
            public void onSuccess(DataBean response) {
                mTimer.schedule(mTimerTask, 1000, 1000);
                //如果发送失败则显示提示信息
                if (!response.noError()) {
                    if (tvPrompt != null) {
                        tvPrompt.setText(response.getMsg());
                    }
                    if (mTimerTask != null) {
                        mTimerTask.cancel();
                    }
                    if (tvCountdown != null) {
                        tvCountdown.setText("重新发送");
                    }
                    time = 0;
                } else {
                    //成功
                    tvPrompt.setText("我们已经发送了验证码到您的手机");
                    tvPhoneNum.setVisibility(View.VISIBLE);

                }
                DialogUtils.getInstance().dismissProgressDialog();
            }
        });


    }


    private void commit() {
        if (etPhoneCode == null || TextUtils.isEmpty(mPhoneNum) || etPassword == null) {
            ToastUtils.showText("程序异常,请重新注册");
            return;
        }
        code = etPhoneCode.getText().toString().trim();
        pwd = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            ToastUtils.makeText("请输入验证码");
            return;
        }
        if (TextUtils.isEmpty(pwd) || pwd.length() < 6 || pwd.length() > 20) {
            ToastUtils.makeText("请输入6-20位的密码");
            return;
        }

        if (request_state) return;

        String stringExtra = intent.getStringExtra(TypeConstant.ACTION_TYPE);
        ParamMap params = new ParamMap();
        String url = getParamConfirmAndUrl(params, intent.getStringExtra(TypeConstant.ACTION_TYPE));

        //修改或找回密码
        if (!TextUtils.equals(intent.getStringExtra(TypeConstant.ACTION_TYPE), TypeConstant.BINDPHONE_ACTION)) {

            addPostRequest(url, new TypeToken<DataBean>() {
            }.getType(), params, new HttpListener<DataBean>() {
                @Override
                public void onStart() {
                    super.onStart();
                    request_state = true;
                    DialogUtils.getInstance().showProgressDialog(ResetPwdActivity.this, "正在提交");
                }

                @Override
                public void onError(VolleyError error) {
                    request_state = false;
                    ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                    DialogUtils.getInstance().dismissProgressDialog();
                }

                @Override
                public void onSuccess(DataBean response) {

                    if (!response.noError()) {
                        ToastUtils.makeText(response.getMsg());
                        DialogUtils.getInstance().dismissProgressDialog();
                    } else {
                        if (TextUtils.equals(intent.getStringExtra(TypeConstant.ACTION_TYPE), TypeConstant.RESETPWD_ACTION)
                                && UserInforManager.getInstance().isLogin()) {
                            UserInforManager.getInstance().getUserInfor().setPassword(pwd);
                            //保存到本地
                            UserInforManager.getInstance().saveUserInfor(UserInforManager.getInstance().getUserInfor());
                        }
                        ToastUtils.makeText("重置密码成功");
                        DialogUtils.getInstance().dismissProgressDialog();
                        setResult(Activity.RESULT_OK);
                        onBackPressed();
                    }
                    request_state = false;
                }
            });
        } else {//绑定手机的操作
            addPostRequest(url, new TypeToken<DataBean<GetTaskBean>>() {
            }.getType(), params, new HttpListener<DataBean<GetTaskBean>>() {
                @Override
                public void onStart() {
                    super.onStart();
                    request_state = true;
                    DialogUtils.getInstance().showProgressDialog(ResetPwdActivity.this, "正在提交");
                }

                @Override
                public void onError(VolleyError error) {
                    request_state = false;
                    ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                    DialogUtils.getInstance().dismissProgressDialog();
                }

                @Override
                public void onSuccess(DataBean<GetTaskBean> response) {
                    if (!response.noError()) {
                        ToastUtils.makeText(response.getMsg());
                        DialogUtils.getInstance().dismissProgressDialog();
                    } else {
                        UserInforManager.getInstance().getUserInfor().setMobile(mPhoneNum);
                        UserInforManager.getInstance().saveUserInfor(UserInforManager.getInstance().getUserInfor());
                        GetTaskBean data = response.getData();
                        if (data != null) {
                            UserInforManager.getInstance().getUserInfor().getTask().setMobileBind("1");
                            UserInforManager.getInstance().saveUserTask(UserInforManager.getInstance().getUserInfor().getTask());
                            ToastUtils.makeText("绑定成功");
                            setResult(Activity.RESULT_OK);
                            onBackPressed();
                        }
                        request_state = false;
                    }
                }
            });
        }

    }


    /**
     * 获取 提交请求的参数和url
     *
     * @param params
     * @param actionType
     * @return
     */
    private String getParamConfirmAndUrl(ParamMap params, String actionType) {

        params.clear();
        String url = "";
        switch (actionType) {
            case TypeConstant.BINDPHONE_ACTION://绑定手机号
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                params.put("captcha", code);
                params.put("password", pwd);
                params.put("mobile", mPhoneNum);
                url = URIContant.BIND_PHONE;
                break;

            case TypeConstant.RESETPWD_ACTION://重设密码
                if (UserInforManager.getInstance().isLogin()) {
                    params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                    params.put("captcha", code);
                    params.put("password", pwd);
                    params.put("mobile", mPhoneNum);
                    params.put("type", "1");//更改密码-1,找回密码-2
                    url = URIContant.CHANGE_PASSWORD;
                }

                break;

            case TypeConstant.FINDPWD_ACTION://找回密码
                params.put("captcha", code);
                params.put("password", pwd);
                params.put("mobile", mPhoneNum);
                params.put("type", "2");//更改密码-1,找回密码-2
                params.put("uid", "");
                url = URIContant.CHANGE_PASSWORD;
                break;
        }

        HttpUtils.ParmsMapMD5(params);
        return url;

    }


    /**
     * 获取发送验证码的参数
     *
     * @param params
     * @param actionType
     */
    private void getParamCode(ParamMap params, String actionType) {
        params.clear();

        switch (actionType) {
            case TypeConstant.BINDPHONE_ACTION://绑定手机号
                params.put("mobile", mPhoneNum);
                params.put("type", TypeConstant.BINDPHONE_CODE);
                params.put("newMobile", "");
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                break;

            case TypeConstant.RESETPWD_ACTION://重设密码
                params.put("mobile", mPhoneNum);
                params.put("newMobile", "");
                params.put("type", TypeConstant.RESETPWD_CODE);
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                break;
            case TypeConstant.FINDPWD_ACTION://忘记密码
                params.put("mobile", mPhoneNum);
                params.put("newMobile", "");
                params.put("type", TypeConstant.FINDPWD_CODE);
                params.put("uid", "");
                break;
        }

        HttpUtils.ParmsMapMD5(params);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_confirm://确定提交
                commit();
                break;
            case R.id.iv_input_cancel://清除内容
                clearContent();
                break;
            case R.id.rb_show_or_hide_pwd://显示/隐藏密码
                showPass();
                break;
            case R.id.tv_countdown://重新发送的点击
                sendCode();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.ResultCode.REQUESTCODE_1 && resultCode == RESULT_OK) {
            onBackPressed();
        }

    }


    /**
     * 显示/隐藏密码
     */

    private void showPass() {
        if (rbShowOrHidePwd == null || etPassword == null) return;

        if (mSelect) {
            rbShowOrHidePwd.setChecked(false);
            mSelect = false;
            //设置EditText文本为隐藏的
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            rbShowOrHidePwd.setChecked(true);
            mSelect = true;
            //设置EditText文本为可见的
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

        }
    }

    /**
     * 清除内容
     */
    private void clearContent() {
        if (etPassword != null) {
            etPassword.setText("");
        }
    }


}
